package g14.sc12project.milestone1.Common;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPathExpression;

import org.apache.log4j.Logger;

import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import g14.sc12project.milestone1.BookStore.AuthorsInfo;
import g14.sc12project.milestone1.BookStore.BookInfo;



/**
 * @author Mohammad
 * 
 */
public class Utils {

	static Logger log = Logger.getLogger(Utils.class.getName());

	public BookInfo getBookInfo(Node bookNode) {

		BookInfo book = new BookInfo();
		try {
			NodeList childNodes = bookNode.getChildNodes();

			for (int i = 0; i < childNodes.getLength(); i++) {
				Node child = childNodes.item(i);
				String name = child.getNodeName();
				String value = child.getTextContent();

				if (name.equalsIgnoreCase(Constants.TITLE)) {
					book.setTitle(value);
				} else if (name.equalsIgnoreCase(Constants.RESOURCE_ID)) {
					book.setResourceID(value);
				} else if (name.equalsIgnoreCase(Constants.ISBN13)) {
					book.setISBN13(value);
				} else if (name.equalsIgnoreCase(Constants.ISBN10)) {
					book.setISBN10(value);
				} else if (name.equalsIgnoreCase(Constants.ISBN13)) {
					book.setISBN13(value);
				} else if (name.equalsIgnoreCase(Constants.AUTHORS)) {
					AuthorsInfo authors = getAuthorsInfo(child);
					book.setAuthors(authors);
				} else if (name.equalsIgnoreCase(Constants.PAGE_NUMBER)) {
					book.setPageNum(Integer.parseInt(value));
				} else if (name.equalsIgnoreCase(Constants.PUBLISHER)) {
					book.setPublisher(value);
				} else if (name.equalsIgnoreCase(Constants.PUBLISH_DATE)) {
					book.setPublishdate(value);
				} else if (name.equalsIgnoreCase(Constants.VERSION)) {
					book.setVersion(value);
				} else if (name.equalsIgnoreCase(Constants.PRICE)) {
					book.setPrice(Double.parseDouble(value));
				}

			}
		} catch (Exception exp) {
			log.error(exp.getMessage());
		}

		return book;

	}

	public AuthorsInfo getAuthorsInfo(Node authorsNode) {
		AuthorsInfo authorsInfo = new AuthorsInfo();
		NodeList authorNodes = authorsNode.getChildNodes();

		ArrayList<String> authors = new ArrayList<String>();
		for (int count = 0; count < authorNodes.getLength(); count++) {
			Node author = authorNodes.item(count);
			String authorName = author.getTextContent();
			authors.add(authorName);
		}

		authorsInfo.setAuthorlist(authors);
		return authorsInfo;
	}

}
